package com.mobartisan.workinglunch;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;


import com.mobartisan.workinglunch.getui_push.NotificitionManager;
import com.mobartisan.workinglunch.getui_push.NotificationReceiver;
import com.mobartisan.workinglunch.ui.activity.ChangeActivity;
import com.mobartisan.workinglunch.ui.activity.ChangePasswordActivity;
import com.mobartisan.workinglunch.ui.activity.LoginActivity;
import com.mobartisan.workinglunch.ui.activity.MainActivity;
import com.mobartisan.workinglunch.ui.base.BaseActivity;
import com.mobartisan.workinglunch.util.FileUtil;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.ToastUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;

import cn.bmob.v3.Bmob;
import okhttp3.internal.Platform;


/**
 * Created by dell on 2016/11/4.
 */

public class SnakeApplication extends Application {
    private static final String TAG = "SnakeApplication";
    private static SnakeApplication context;
    private DisplayImageOptions options = null;
    public static Dialog dialog= null;

    public static SnakeApplication getInstance() {
        return context;
    }

    private static DemoHandler handler;
    public static MainActivity mainActivity;
    public static LoginActivity loginActivity;
    public static ChangeActivity changeActivity;
    private static boolean activityVisible;
    public static BaseActivity baseActivity;
    public static ChangePasswordActivity changePasswordActivity;
    String contents;
    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public static String payloadData;


    public static boolean isActivityVisible() {
        return activityVisible;
    }

    public static void activityResumed() {
        activityVisible = true;
    }

    public static void activityPaused() {
        activityVisible = false;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
//        initializeImageLoder(this);
        Bmob.initialize(this, "fda3427c896b8c18dbf6ddab0e515a8f", "Bmob");
        /** 初始化 SharedPreferencesUtil  用来存储本地数据*/
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
        SharedPreferencesUtil.setInstance(sharedPreferencesUtil);
        if (handler == null) {
            handler = new DemoHandler();
        }
    }

    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }

    public void exitApp() {

        System.runFinalization();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static class DemoHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    payloadData = msg.obj.toString();
                    if (changeActivity != null) {
                        showWay();

                    } else if (changePasswordActivity != null) {
                        showWay();
                    } else if (mainActivity != null) {
                        showWay();
                    }
                    break;
            }
        }
    }

    private static void showWay() {
        if (isActivityVisible()) {
            baseActivity.dismissDilog();
            baseActivity.showDilog(payloadData);
        } else {
            NotificitionManager.showNofi(context, "提醒", payloadData, NotificationReceiver.class);
        }
    }

    /**
     * 初始化Fresco图片加载
     */
    private void initializeImageLoder(Application application) {
        //Fresco.initialize(getApplicationContext());  File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), FileUtil.getCacheImgPath(getApplicationContext()));
        File cacheDir = StorageUtils.getOwnCacheDirectory(application, FileUtil.getCacheImgPath(application.getApplicationContext()));
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageOnLoading(R.mipmap.ic_launcher)
                .cacheInMemory(true)
                .resetViewBeforeLoading(false)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .cacheOnDisk(true)
                //.displayer(new RoundedBitmapDisplayer(5))
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(application.getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCacheFileCount(100) //缓存的文件数量
                .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
                .defaultDisplayImageOptions(options)
                .imageDownloader(new BaseImageDownloader(application.getApplicationContext(), 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
//	        .writeDebugLogs() // Remove for release app
                .build();//开始构建
        ImageLoader.getInstance().init(config);
    }

    public DisplayImageOptions getOptions() {
        return options;
    }
}
